package edu.ptit.app;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import edu.ptit.jad.data.MatrixUtils;
import edu.ptit.jad.model.ContentSimilarity;
import edu.ptit.jad.preprocess.app.LdaModel;

public class AppTopNAuthor {

	public static void main(String[] args) throws Exception {

		// Load the model.
		LdaModel model = new LdaModel();
		model.loadModel("data/input/at.model");

		process(model, "data/input/ads_at.theta","data/input/ads_at_cats.theta");

	}

	public static void process(LdaModel model, String fileDir, String fileSave)
			throws Exception {

		File file = new File(fileSave);
		BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
				new FileOutputStream(file), "UTF8"));

		double[][] matrix = MatrixUtils.readMatrix(fileDir);

		int nRows = matrix.length;
		int nCols = matrix[0].length;

		out.write(nRows + "\n");
		out.write(model.getNumTopics() + "\n");

		// model.getNumTopics() = number of author at _at.model
		double[][] author_topic = new double[nRows][model.getNumTopics()];

		for (int i = 0; i < nRows; i++) {

			List<ContentSimilarity> contentSimilaritys = new ArrayList<ContentSimilarity>();

			for (int j = 0; j < nCols; j++) {

				contentSimilaritys.add(new ContentSimilarity(j + 1,
						matrix[i][j]));

			}

			// get top 50 topics
			ContentSimilarity[] sis = ContentSimilarity.getTopN(
					contentSimilaritys, 30);

			String topN = "";
			for (ContentSimilarity si : sis) {

				topN += si.getId() + " ";

			}
			
			System.out.println(topN);

			double[] p = model.inferenceFast(topN.trim().split(" "));

			for (int k = 0; k < p.length; k++)
				out.write(p[k] + " ");

			out.write("\n");

		}
		
		out.close();

	}

}
